package com.example.springboot.handle;

import com.example.springboot.exception.GirlException;
import com.example.springboot.domain.Result;
import com.example.springboot.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    /**
     *  异常进来后，在这里统一处理，目的是 统一返回的格式：Result
     */
    @ExceptionHandler(value = Exception.class)  //这里声明的是要捕获的哪个异常类，这才是捕获了
    @ResponseBody
    public Result handler(Exception e){
        if(e instanceof GirlException){
            GirlException girlException = (GirlException) e;
            return ResultUtil.error(girlException.getCode(),girlException.getMessage());
        }else{
            logger.error("【系统异常】{}", e);
            return ResultUtil.error(-1,"未知错误");
        }
    }

}
